import React, { useEffect, useRef } from "react";
import * as echarts from "echarts";

const axiosOption = {
  textStyle: {
    color: "#333",
  },
  tooltip: {
    trigger: "axis",
  },
  xAxis: {
    type: "category",
    data: [],
    axisLine: {
      lineStyle: {
        color: "#17b3a3",
      },
    },
    axisLabel: {
      interval: 0,
      color: "#333",
    },
  },
  yAxis: [
    {
      type: "value",
      axisLine: {
        lineStyle: {
          color: "#17b3a3",
        },
      },
    },
  ],
  color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
  series: [],
};

const normalOption = {
  tooltip: {
    trigger: "item",
  },
  color: [
    "#0f78f4",
    "#dd536b",
    "#9467bd",
    "#a6a6a6",
    "#e7c050",
    "#588dd5",
    "#f5994e",
    "#c05050",
  ],
  series: [],
};

const Echarts = ({ style, chartData, isAxisChart = true }) => {
  const echartRef = useRef();
  let echartObj = useRef(null);
  useEffect(() => {
    console.log('接收到的图表数据:', chartData);
    let options;
    
    echartObj.current = echarts.init(echartRef.current);
    
    // 添加resize监听
    const handleResize = () => echartObj.current.resize();
    window.addEventListener('resize', handleResize);
    
    if (isAxisChart) {
      axiosOption.xAxis.data = chartData.xData;
      axiosOption.series = chartData.series;
      options = axiosOption;
    } else {
      normalOption.series = chartData.series;
      options = normalOption;
    }
    echartObj.current.setOption(options);
    
    // 组件卸载时移除监听
    return () => window.removeEventListener('resize', handleResize);
  }, [chartData]);

  return <div style={style} ref={echartRef}></div>;
};

export default Echarts;
